﻿#include "MainWindow.h"
#include "ui_MainWindow.h"

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
        setWindowIcon(QIcon(":/tools/icon.png"));
    trayIconMenu = new QMenu(this);

    doc = new QDomDocument("mydocument");
    QFile file(QCoreApplication::applicationDirPath()+"/"+"config.xml");
        //qDebug()<<QCoreApplication::applicationDirPath()+"/"+"config.xml";
    if (file.open(QIODevice::ReadOnly))
    {

        if (doc->setContent(&file)) {
            QDomNodeList l = doc->elementsByTagName("node");
            uint i=0;
            for(;i<l.length();i++){
                QString key = l.at(i).firstChildElement("name").text().trimmed();
                QString value = l.at(i).firstChildElement("hosts").text().trimmed();;
                settings.insert(key,value);
                if(settings.contains(key)){

                    QPushButton *b = new QPushButton();
                    connect(b,SIGNAL(clicked()),this,SLOT(setHosts()));
                    b->setText(key);
                    ui->verticalLayout->addWidget(b);


                    QAction *action = new QAction(key, this);
                    connect(action, SIGNAL(triggered()), this, SLOT(setHostsIcon()));
                    trayIconMenu->addAction(action);
                }

            }
            ui->statusBar->showMessage("加载配置文件成功.");
        }
        file.close();
    }
	QDesktopWidget* desktop = QApplication::desktop();
	move((desktop->width() - this->width())/2, (desktop->height() - this->height())/2);


    createActions();
    createTrayIcon();
    trayIcon = new QSystemTrayIcon(this);
        trayIcon->setIcon(QIcon(":/tools/icon.png"));

    connect(trayIcon, SIGNAL(activated(QSystemTrayIcon::ActivationReason)),
            this, SLOT(iconActivated(QSystemTrayIcon::ActivationReason)));

    trayIcon->setContextMenu(trayIconMenu);
    trayIcon->show();

}
void MainWindow::setHost(QString key,bool isTray){

    #ifdef Q_OS_WIN32
    QString fileName("c:/windows/system32/drivers/etc/hosts");
    #else
    QString fileName("/etc/hosts");
    #endif

    QString value = settings.value(key);

    QFile f(fileName);
    if(f.open(QIODevice::WriteOnly)){
        f.write(value.toLocal8Bit());

        f.close();

        #ifdef Q_OS_WIN32
             QProcess::execute("ipconfig",QStringList("/flushdns"));
        #else
             if(QFile::exists("/etc/init.d/dns-clean"))             QProcess::execute("/etc/init.d/dns-clean");
             if(QFile::exists("/etc/init.d/nscd"))             QProcess::execute("/etc/init.d/nscd",QStringList("restart"));
             if(QFile::exists("/etc/init.d/dnsmasq"))             QProcess::execute("/etc/init.d/dnsmasq",QStringList("restart"));

        #endif
             QString msg="成功设置:"+key;
             if(isTray){
                 trayIcon->showMessage("提示",msg,QSystemTrayIcon::NoIcon);
             }else{
                 ui->statusBar->showMessage("提示:"+msg);
             }
    }else{
        #ifdef Q_OS_WIN32
                QString msg="没有权限,请用管理员账号运行.";
        #else
                QString msg="没有权限,请用root账号运行.";
        #endif
        if(isTray){
            trayIcon->showMessage("错误",msg,QSystemTrayIcon::Warning);
        }else{
            ui->statusBar->showMessage("错误:"+msg);
        }
    }

}
void MainWindow::iconActivated(QSystemTrayIcon::ActivationReason reason)
 {
     switch (reason) {
     case QSystemTrayIcon::Trigger:
     case QSystemTrayIcon::DoubleClick:
     case QSystemTrayIcon::MiddleClick:
         show();
     default: ;
     }
 }
void MainWindow::setHostsIcon(){
    QAction * b = qobject_cast<QAction*>(sender());
    Q_ASSERT(b);
   // qDebug()<<b->text();
    setHost(b->text(),true);

}

void MainWindow::setHosts(){
    QPushButton * b = qobject_cast<QPushButton*>(sender());
    Q_ASSERT(b);
   // qDebug()<<b->text();
    setHost(b->text(),false);
}
void MainWindow::createActions()
{
    quitAction = new QAction(tr("退出"), this);
    connect(quitAction, SIGNAL(triggered()), qApp, SLOT(quit()));
}
void MainWindow::createTrayIcon()
{
    trayIconMenu->addSeparator();
    trayIconMenu->addAction(quitAction);
}

MainWindow::~MainWindow()
{
	trayIcon->hide();
	trayIconMenu->deleteLater();
	trayIcon->deleteLater();
    delete ui;
}
